<?php

class Journal2Minifier {

    private $styles = array();
    private $scripts = array(
        'header'    => array(),
        'footer'    => array()
    );

    private $minify = false;

    public function addStyle($href) {
        $this->styles[md5($href)] = $href;
    }

    public function addScript($src, $position = 'header') {
        $this->scripts[$position][md5($src)] = $src;
    }

    public function css() {
        $res = '';
        if ($this->minify) {
            $res .= $this->printStyle($this->getCSSUrl());
        } else {
            foreach ($this->styles as $style) {
                $res .= $this->printStyle($style);
            }
        }
        return $res;
    }

    public function js($position = 'header') {
        $res = '';
        if ($this->minify) {
            $res .= $this->printScript($this->getJSUrl($position));
        } else {
            foreach ($this->scripts[$position] as $script) {
                $res .= $this->printScript($script);
            }
        }
        return $res;
    }

    public function setMinify($value) {
        $this->minify = $value;
    }

    private function getCSSUrl() {
        return 'min/?f=' . implode(',', $this->styles);
    }

    private function getJSUrl($position = 'header') {
        return 'min/?f=' . implode(',', $this->scripts[$position]);
    }

    private function printStyle($href) {
        $del = $this->minify ? '&amp;' : '?';
        return '<link rel="stylesheet" href="' . $href . $del . 'ver=' . JOURNAL_VERSION . '"/>' . PHP_EOL;
    }

    private function printScript($src) {
        $del = $this->minify ? '&amp;' : '?';
        return '<script type="text/javascript" src="' . $src . $del . 'ver=' . JOURNAL_VERSION . '"></script>' . PHP_EOL;
    }
}